<?php

/**
 * 印尼短信接口：支持下发短信（支持群发），可用于 找回密码，短信告警，发送活动通知等
    sample:  
curl -X POST -H 'Content-Type:application/json' --data '{"account":"I6166714","password":"***","msg":"Mohon masukkan kode verifikasi: 7210 dalam 5 menit. now time: 2019-11-14 16:00:32","mobile":"6281282597771"}' http://intapi.253.com/send/json

 */

class SMS_CL253 extends SMS_Abstract {

    /**
     * 帐号
     *
     * */
    private $_account = '';

    /**
     * 密钥
     *
     * */
    private $_seckey = '';
    
    /**
     * 发放方名称
     * @var type 
     */
    private $_senderName = '';
    
    /**
     * 调试模式
     * @var type 
     */
    public $debugMode = false;

    /**
     * 构造函数
     * @param <type> $option
     */
    public function __construct($option = array()) {

        if (isset($option['account'])) {
            $this->setAccount($option['account'], $option['seckey']);
        }
        if (isset($option['sender_name'])) {
            $this->_senderName = $option['sender_name'];
        }

        parent::__construct($option);
    }

    /**
     * 设置帐号
     * @param <type> $account
     * @param <type> $seckey
     * */
    public function setAccount($account, $seckey) {

        $this->_account = $account;
        $this->_seckey = $seckey;
    }

    /**
     * 发送短信
     * @param <type> $mobile 接收手机号，必须以 62 开头
     * @param <type> $content （必须 utf8 格式）
     *
     * @return 发送成功条数
     */
    public function send($mobile, $content) {

        $param = array(
            'account' => $this->_account,
            'password' => $this->_seckey,
            'msg' => $content,
            'mobile' => '62'.$mobile,
        );
        $url = 'http://intapi.253.com/send/json';
        $headers = array(
            'Content-Type:application/json',
        );

        try {
            $res = $this->_send($url, $param, $headers);
        } catch (Exception $ex) {
            V::log($ex);
            return false;
        }
        
        $data = json_decode($res, true);
        if (!$data || $data['code'] != 0) {
            return false;
        }

        return true;
    }

    /**
     * 发送请求
     * 
     * @param type $url
     * @param type $postFields
     * @param type $httpHeaders
     * @return type
     * @throws Exception
     */
    public function _send($url, $postFields, $httpHeaders) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

        //https request
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        // body
        if (is_array($postFields)) {
            $postFields = json_encode($postFields);
        }
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        
        // header
        if (is_array($httpHeaders) && 0 < count($httpHeaders)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders);
        }
        
        $response = curl_exec($ch);

        // debug info start //
        if ($this->debugMode) {
            echo '----- curl call -----', PHP_EOL;
            echo 'url: ', $url, PHP_EOL;
            if (!empty($postFields)) {
                echo 'body: ', $postFields, PHP_EOL;
            }
            if (!empty($httpHeaders)) {
                echo 'header: ', "\n  ", implode("\n  ", $httpHeaders), PHP_EOL;
            }
            echo 'response: ', $response, PHP_EOL, PHP_EOL;
        }
        // debug info end //

        if (curl_errno($ch)) {
            throw new Exception(curl_error($ch), 0);
        } else {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode) {
                throw new Exception($response, $httpStatusCode);
            }
        }
        curl_close($ch);
        return $response;
    }

}